package com.ruoyi.common.utils.ping;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.channels.SocketChannel;

public class PortUsageChecker {

    private static final Logger log = LoggerFactory.getLogger(PortUsageChecker.class);

    //判断端口是否占用
    public static boolean isPortInUse(String host, int port) {
        try (SocketChannel socketChannel = SocketChannel.open()) {
            Socket socket = socketChannel.socket();
            SocketAddress socketAddress = new InetSocketAddress(host, port);
            socket.connect(socketAddress, 1000); // 1 second timeout

            // 如果连接成功，则端口开放
            return socket.isConnected();

        } catch (IOException e) {
            // 捕获异常表示端口未被占用
            log.error("ip: {}, 端口: {}, 检测异常: {}", host, port, e);
        }
        return false;
    }

    public static void main(String[] args) {
        String remoteHost = "hao.360.cn";  // 例如：example.com
        int remotePort = 80;  // 要检测的远程服务器端口号

        boolean isPortInUse = isPortInUse(remoteHost, remotePort);

        if (isPortInUse) {
            System.out.println("端口开放");
        } else {
            System.out.println("端口关闭");
        }
    }

}
